// common/services/network/api_response.dart
class ApiResponse<T> {
  final bool success;
  final int code;
  final String message;
  final T? data;
  final dynamic originalData;
  
  ApiResponse({
    required this.success,
    required this.code,
    required this.message,
    this.data,
    this.originalData,
  });
  
  // 成功响应
  factory ApiResponse.success({
    required T data,
    String message = '请求成功',
    int code = 200,
  }) {
    return ApiResponse<T>(
      success: true,
      code: code,
      message: message,
      data: data,
    );
  }
  
  // 失败响应
  factory ApiResponse.error({
    required String message,
    int code = -1,
    dynamic originalData,
  }) {
    return ApiResponse<T>(
      success: false,
      code: code,
      message: message,
      originalData: originalData,
    );
  }
  
  // 从JSON创建响应
  factory ApiResponse.fromJson(
    Map<String, dynamic> json,
    T Function(dynamic)? fromJsonT,
  ) {
    try {
      final success = json['success'] ?? json['code'] == 200;
      final code = json['code'] ?? (success ? 200 : -1);
      final message = json['message'] ?? json['msg'] ?? '';
      final data = json['data'];
      
      T? parsedData;
      if (success && data != null && fromJsonT != null) {
        parsedData = fromJsonT(data);
      }
      
      return ApiResponse<T>(
        success: success,
        code: code,
        message: message,
        data: parsedData,
        originalData: json,
      );
    } catch (e) {
      return ApiResponse.error(
        message: '数据解析失败: $e',
        originalData: json,
      );
    }
  }
  
  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'success': success,
      'code': code,
      'message': message,
      'data': data,
    };
  }
  
  @override
  String toString() {
    return 'ApiResponse{success: $success, code: $code, message: $message, data: $data}';
  }
}
